﻿using Client;
using Shared.Method;
using Shared.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Update.Model;

namespace Update
{
    public partial class FormUpdate : Form
    {
        private SoftwareMessage _softMsg = null;
        public FormUpdate()
        {
            InitializeComponent();
        }

        private void GetSoftwareMsg()
        {
            //从XML文件中获得SOFT的信息
            string softName = ConfigUpdate.GetXmlConfigSoftware(SharedMessage.DEFAULT);
            string softFolder = ConfigUpdate.GetXmlConfigSoftware(SharedMessage.FOLDER);

            if (!string.IsNullOrEmpty(softName) && !string.IsNullOrEmpty(softFolder))
            {
                _softMsg = new SoftwareMessage();
                _softMsg.SoftwareName = softName;
                _softMsg.SoftFolder = softFolder;
            }
        }

        private void FormUpdate_Load(object sender, EventArgs e)
        {
            //如果没有软件信息，则打开配置文档
            GetSoftwareMsg();
            if (_softMsg == null)
            {
                FormConfig config = new FormConfig();
                config.ShowDialog();
            }
        }

        private void buttonCheckUpdate_Click(object sender, EventArgs e)
        {
            Action d = new Action(CheckUpdate);
            d.BeginInvoke(null, null);
        }

        private void buttonConfigChg_Click(object sender, EventArgs e)
        {
            FormConfig config = new FormConfig();
            config.ShowDialog();
        }

        private void CheckUpdate()
        {
            GetSoftwareMsg();
            if (_softMsg == null)
            {
                MessageBox.Show("未能获取软件信息，请打开配置文件配置");
                return;
            }


            //获取文件所有信息
            if (DownSoftMessage() == false)
            {
                MessageBox.Show("未能从服务器上获得软件信息", "更新失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            //将当前目录保存为ZipFolder
            _softMsg.UpdateZipFolder = Environment.CurrentDirectory;
            AppendRichTextBox("开始检查更新……");

            //获取相关目录相关文件是否存在，如果不存在则直接下载升级软件
            if (!Directory.Exists(_softMsg.SoftFolder))
            {
                //MessageBox.Show("before createDirectory");
                Directory.CreateDirectory(_softMsg.SoftFolder);
                //下载软件
                //MessageBox.Show("before httpdown");
                if(HttpClass.HttpDownload(_softMsg.LinkAddress, Path.Combine(_softMsg.UpdateZipFolder, _softMsg.UpdateZipFile)) == false)
                {
                    MessageBox.Show("下载软件失败");
                }
                //ProcessClass.KillProcess(_softMsg.SoftwareName);
                //更新
                //MessageBox.Show("before updateSoft");
                UpdateSoftware();
                //关闭
            }
            else if( !File.Exists(Path.Combine(_softMsg.SoftFolder, _softMsg.SoftwareNameExe)))
            {
                //下载软件
                if (HttpClass.HttpDownload(_softMsg.LinkAddress, Path.Combine(_softMsg.UpdateZipFolder, _softMsg.UpdateZipFile)) == false)
                {
                    MessageBox.Show("下载软件失败");
                }
                //ProcessClass.KillProcess(_softMsg.SoftwareName);
                //更新
                UpdateSoftware();
            }
            else//directory存在，software存在
            {
                //获得软件信息
                //①软件版本
                //从服务器上获取软件版本信息

                FileVersionInfo info = FileVersionInfo.GetVersionInfo(Path.Combine(_softMsg.SoftFolder, _softMsg.SoftwareNameExe));
                if (info.FileVersion == _softMsg.NewVersion
                    && (MessageBox.Show("软件版本一致，是否更新？","提示", MessageBoxButtons.OKCancel) == DialogResult.Cancel))
                {
                    return;
                }

                //下载软件
                if (HttpClass.HttpDownload(_softMsg.LinkAddress, Path.Combine(_softMsg.UpdateZipFolder, _softMsg.UpdateZipFile)) == false)
                {
                    MessageBox.Show("下载软件失败");
                }

                //ProcessClass.KillProcess(_softMsg.SoftwareName);
                //更新
                UpdateSoftware();
            }
            
        }

        private bool ClearFolder(string folder)
        {
            try
            {
                //清空目录
                if (Directory.Exists(folder) == false)
                {
                    MessageBox.Show("所需清除的目录不存在");
                    return true;
                }

                DirectoryInfo dir = new DirectoryInfo(folder);
                var listDir = dir.GetDirectories();
                for (int i = 0; i < listDir.Length; i++)
                {
                    ClearFolder(listDir[i].FullName);//递归删除目录和文件
                    Directory.Delete(listDir[0].FullName);//删除目录
                }

                var listFile = dir.GetFiles();
                for (int j = 0; j < listFile.Length; j++)
                {
                    File.Delete(listFile[j].FullName);
                }

                return true;
            }
            catch
            {
                return false;
            }
        }

        private static void ChangeFileName(string lastName, string newName, string Folder)
        {
            try
            {
                string lastFilePath = Path.Combine(Folder, lastName);
                if (File.Exists(lastFilePath))
                {
                    File.Move(lastFilePath, Path.Combine(Folder, newName));
                    Console.WriteLine("修改名称成功");
                }
                else
                {
                    Console.WriteLine("软件不存在");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private  bool DownSoftMessage()
        {
            if (string.IsNullOrEmpty(_softMsg.SoftwareName))
            {
                Console.WriteLine("默认软件名称为空");
                return false;
            }
            try
            {
                //Console.WriteLine("IS HERE 1");
                var softW = new SOFTWARE();
                softW.SetWhere();
                //Console.WriteLine("IS HERE 4");
                softW.NAME = _softMsg.SoftwareName;
                //Console.WriteLine("IS HERE 5");
                var selectSoft = MethodWcf.SelectSoftwareClient(softW);
                //Console.WriteLine("IS HERE 2");
                if (!selectSoft.result)
                {
                    Console.WriteLine("未能从数据库获得软件信息");
                    return false;
                }
                //Console.WriteLine("IS HERE 3");
                _softMsg.NewVersion = selectSoft.value[0].VERSION;
                _softMsg.LinkAddress = selectSoft.value[0].LINK_ADDRESS;
                _softMsg.UpdateZipFile = selectSoft.value[0].FILE_NAME;

                return true;
            }
            catch
            {
                return false;
            }
        }

        private bool UpdateSoftware()
        {
            //关闭相关进程
            //MessageBox.Show("before killprocess");
            AppendRichTextBox("开始关闭相关进程……");
            if (ProcessClass.KillProcess(_softMsg.SoftwareName) == false) { Console.WriteLine("更新失败，未能关闭相关进程"); return false; }
            AppendRichTextBox("关闭相关进程成功");
            System.Threading.Thread.Sleep(1000);
            //MessageBox.Show("before unzip");
            //清空目录下的所有文件和目录
            AppendRichTextBox("开始清除目录……");
            if (ClearFolder(_softMsg.SoftFolder) == false)
            {
                MessageBox.Show("清除文件失败，请检查文件占用情况");
                return false;
            }
            AppendRichTextBox("清除目录成功");

            //解压文件到文件夹
            AppendRichTextBox("开始解压软件……");
            if (ZipHelper.UnZip(Path.Combine(_softMsg.UpdateZipFolder,_softMsg.UpdateZipFile), _softMsg.SoftFolder) == false)
            {
                MessageBox.Show("解压文件失败");
                return false;
            }
            AppendRichTextBox("解压软件完成");
            AppendRichTextBox("删除下载的ZIP文件……");

            //删除ZIP文件
            File.Delete(Path.Combine(_softMsg.UpdateZipFolder, _softMsg.UpdateZipFile));
            AppendRichTextBox("删除下载的ZIP文件成功");
            AppendRichTextBox("更新软件完成，开启软件……");
            //开启相关进程
            ProcessClass.StartProcess(_softMsg.SoftwareNameExe, _softMsg.SoftFolder);
            return true;
        }

        private void richTextBoxMsg_TextChanged(object sender, EventArgs e)
        {
            this.richTextBoxMsg.SelectionStart = this.richTextBoxMsg.Text.Length;
            this.richTextBoxMsg.ScrollToCaret();
        }

        //将信息检查信息窗口
        private void AppendRichTextBox(string value)
        {
            if (this.richTextBoxMsg.InvokeRequired)
            {
                Action<string> d = new Action<string>(AppendRichTextBox);
                Invoke(d, new object[] { value });
            }
            else
            {
                if (this.richTextBoxMsg.TextLength >= 1000)
                    this.richTextBoxMsg.Clear();
                this.richTextBoxMsg.AppendText(value);
                this.richTextBoxMsg.AppendText("\n");
            }
        }
    }
}
